<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="conversation-list" :class="{ 'mobile-hidden': isMobileMenuHidden }">
      <div class="list-header">
        <h3>ChatGPT</h3>
        <el-button 
          type="primary" 
          @click="createNewConversation" 
          class="new-chat-btn"
        >
          <el-icon><Plus /></el-icon>新建会话
        </el-button>
      </div>
      
      <el-scrollbar>
        <div class="conversation-groups">
          <div class="group-title">今天</div>
          <div 
            v-for="conv in conversations" 
            :key="conv.id"
            class="conversation-item"
            :class="{ active: currentConversation?.id === conv.id }"
            @click="selectConversation(conv)"
          >
            <el-icon><ChatDotRound /></el-icon>
            <span class="conversation-name">{{ conv.name || '新对话' }}</span>
            <div class="item-actions" v-if="currentConversation?.id === conv.id">
              <el-icon @click.stop="handleRename(conv)"><Edit /></el-icon>
              <el-icon @click.stop="handleDelete(conv)"><Delete /></el-icon>
            </div>
          </div>
        </div>
      </el-scrollbar>

      <!-- 添加底部退出登录按钮 -->
      <div class="list-footer">
        <el-button 
          @click="handleLogout"
          class="logout-btn"
        >
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </el-button>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <!-- 移动端菜单按钮 -->
      <div class="mobile-menu-button" @click="toggleMobileMenu">
        <el-icon><Menu /></el-icon>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageList">
        <el-scrollbar ref="scrollbar">
          <div class="message-wrapper">
            <!-- 添加欢迎界面 -->
            <div v-if="!currentConversation?.id && messages.length === 0" class="welcome-screen">
              <h1 class="welcome-title">有什么可以帮忙的?</h1>
              <div class="suggestions">
                <div class="suggestion-row">
                  <div class="suggestion-item">
                    <el-icon><Picture /></el-icon>
                    <span>校园规则</span>
                  </div>
                  <div class="suggestion-item">
                    <el-icon><Document /></el-icon>
                    <span>总结文本</span>
                  </div>
                </div>
                <div class="suggestion-row">
                  <div class="suggestion-item">
                    <el-icon><ChatLineRound /></el-icon>
                    <span>提建议</span>
                  </div>
                  <div class="suggestion-item">
                    <el-icon><More /></el-icon>
                    <span>更多</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 现有的消息列表 -->
            <div 
              v-for="msg in messages" 
              :key="msg.id" 
              class="message-item"
              :class="msg.role"
            >
              <div class="avatar">
                <el-icon v-if="msg.role === 'user'"><User /></el-icon>
                <el-icon v-else><Service /></el-icon>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="message-role">{{ msg.role === 'user' ? '我' : 'AI' }}</span>
                  <span class="message-time">{{ msg.time }}</span>
                </div>
                <div class="message-text markdown-body" v-html="formatMessage(msg.content)"></div>
                <div class="message-actions">
                  <el-icon 
                    v-if="msg.role === 'assistant'" 
                    @click="copyMessage(msg.content)"
                    title="复制"
                  >
                    <CopyDocument />
                  </el-icon>
                  <el-icon 
                    v-if="msg.role === 'assistant'" 
                    @click="handleFeedback(msg.id, msg.liked ? null : 'like', msg.content)"
                    :class="{ 'active': msg.liked === 'like' }"
                    title="点赞"
                  >
                    <TopRight class="thumb" />
                  </el-icon>
                  <el-icon 
                    v-if="msg.role === 'assistant'" 
                    @click="handleFeedback(msg.id, msg.liked ? null : 'dislike', msg.content)"
                    :class="{ 'active': msg.liked === 'dislike' }"
                    title="不喜欢"
                  >
                    <BottomRight class="thumb" />
                  </el-icon>
                </div>
              </div>
            </div>
            <!-- 正在输入的消息 -->
            <div 
              v-if="streamingMessage || isWaiting" 
              class="message-item assistant"
            >
              <div class="avatar">
                <el-icon><Service /></el-icon>
              </div>
              <div class="message-content">
                <template v-if="streamingMessage">
                  <div class="message-text" v-html="formatMessage(streamingMessage)"></div>
                </template>
                <div v-else-if="isWaiting" class="typing-indicator">
                  <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-wrapper">
          <el-input
            v-model="messageInput"
            type="textarea"
            :rows="1"
            placeholder="发送消息... (可以粘贴图片)"
            @keyup.enter.ctrl="sendMessage"
            @paste="handlePaste"
            resize="none"
            :autosize="{ minRows: 1, maxRows: 4 }"
          />
          <el-button 
            class="send-button"
            :class="{ 'is-responding': isResponding }"
            type="primary" 
            circle
            @click="isResponding ? stopResponse() : sendMessage()"
            :loading="sending && !isResponding"
          >
            <el-icon>
              <component :is="isResponding ? 'Close' : 'ArrowUp'" />
            </el-icon>
          </el-button>
        </div>
        <div class="input-tip">
          使用 Ctrl + Enter 发送消息
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { 
  Plus,
  ChatDotRound,
  Menu,
  User,
  Edit,
  Delete,
  CopyDocument,
  Service,
  SwitchButton,
  TopRight,
  BottomRight,
  ArrowUp,
  Picture,
  Document,
  ChatLineRound,
  More,
  Close
} from '@element-plus/icons-vue'
import { 
  getConversations, 
  getMessages, 
  sendMessage as apiSendMessage,
  renameConversation,
  sendFeedback,
  uploadFile,
  deleteConversation,
  logout
} from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'  // 使用更明显的代码高亮主题
import { useRouter } from 'vue-router'

const conversations = ref([])
const currentConversation = ref(null)
const messages = ref([])
const messageInput = ref('')
const sending = ref(false)
const selectedFiles = ref([])
const streamingMessage = ref('')  // 用于存储正在流式接收的消息
const scrollbar = ref(null)
const isMobileMenuHidden = ref(window.innerWidth <= 768)
const isWaiting = ref(false)
const isResponding = ref(false)  // 用于标记 AI 是否正在响应
const currentTaskId = ref(null)

// 在 script setup 顶部添加
const CACHE_KEY = 'chat_message_cache'

// 初始化时从 localStorage 加载缓存
const messageCache = ref(JSON.parse(localStorage.getItem(CACHE_KEY) || '{}'))

// 监听缓存变化，保存到 localStorage
watch(messageCache.value, (newCache) => {
  localStorage.setItem(CACHE_KEY, JSON.stringify(newCache))
}, { deep: true })

const USER_ID = import.meta.env.VITE_USER_ID
const router = useRouter()

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    try {
      return `<div class="code-block">
                <div class="code-header">
                  <span class="code-lang">${language}</span>
                </div>
                <pre><code class="hljs language-${language}">${hljs.highlight(code, { language }).value}</code></pre>
              </div>`;
    } catch (err) {
      console.error('代码高亮失败:', err);
      return `<pre><code class="hljs">${code}</code></pre>`;
    }
  },
  breaks: true,
  gfm: true,
  langPrefix: 'language-'
})

// 获取会话列表
const fetchConversations = async () => {
  try {
    const res = await getConversations()
    conversations.value = Array.isArray(res.data) ? res.data : []
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
    conversations.value = []
  }
}

// 获取消息列表
const fetchMessages = async (conversationId) => {
  try {
    if (!conversationId) return

    // 从服务器获取消息
    const res = await getMessages(conversationId)
    
    if (res.data && Array.isArray(res.data)) {
      const newMessages = []
      res.data.forEach(msg => {
        const queryTime = msg.query_time ? new Date(msg.query_time * 1000) : new Date()
        const answerTime = msg.answer_time ? new Date(msg.answer_time * 1000) : new Date()

        const formatTime = (date) => {
          return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          })
        }

        if (msg.query) {
          newMessages.push({
            id: msg.id,
            role: 'user',
            content: msg.query,
            time: formatTime(queryTime)
          })
        }
        if (msg.answer) {
          newMessages.push({
            id: msg.id,
            role: 'assistant',
            content: msg.answer,
            time: formatTime(answerTime)
          })
        }
      })
      
      // 始终更新缓存和显示的消息
      messageCache.value[conversationId] = newMessages
      messages.value = newMessages
    }
  } catch (error) {
    if (error.response?.status === 404) {
      // 如果会话不存在，清空消息
      messageCache.value[conversationId] = []
      messages.value = []
      return
    } else {
      console.error('获取消息列表失败:', error)
      ElMessage.error('获取消息列表失败')
    }
  }
}

// 选择会话
const selectConversation = async (conv) => {
  if (!conv?.id) return
  
  try {
    // 如果当前有流式消息，先将其保存到消息列表中
    if (streamingMessage.value && currentConversation.value) {
      const currentTime = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })

      // 将流式消息添加到当前会话的消息缓存中
      if (messageCache.value[currentConversation.value.id]) {
        messageCache.value[currentConversation.value.id].push({
          id: Date.now(),
          role: 'assistant',
          content: streamingMessage.value,
          time: currentTime
        })
      }
    }

    // 清空流式消息
    streamingMessage.value = ''
    isWaiting.value = false
    
    currentConversation.value = conv
    await fetchMessages(conv.id)
    await scrollToBottom()
  } catch (error) {
    console.error('获取消息失败:', error)
    ElMessage.error('获取消息失败')
  }
}

// 格式化消息内容
const formatMessage = (content) => {
  if (!content) return ''
  try {
    // 解析 Markdown 内容
    return marked(content)
  } catch (error) {
    console.error('Markdown 解析失败:', error)
    return content
  }
}

// 切换移动端菜单
const toggleMobileMenu = () => {
  isMobileMenuHidden.value = !isMobileMenuHidden.value
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
  if (window.innerWidth > 768) {
    isMobileMenuHidden.value = false
  }
})

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  const scrollbarEl = scrollbar.value?.$el.querySelector('.el-scrollbar__wrap')
  if (scrollbarEl) {
    // 使用平滑滚动
    scrollbarEl.scrollTo({
      top: scrollbarEl.scrollHeight,
      behavior: 'smooth'
    })
  }
}

// 添加一个函数来解析消息中的图片ID
const extractImageIds = (message) => {
  const regex = /!\[.*?\]\((.*?)\)/g
  const matches = [...message.matchAll(regex)]
  return matches.map(match => match[1])
}

// 添加一个函数来提取纯文本内容
const extractPureText = (message) => {
  // 移除所有的图片标记 ![xxx](xxx)
  return message.replace(/!\[.*?\]\(.*?\)/g, '').trim()
}

// 修改 sendMessage 函数，保存任务ID
const sendMessage = async () => {
  if (!messageInput.value.trim() || sending.value) return
  
  sending.value = true
  streamingMessage.value = ''
  isWaiting.value = true
  isResponding.value = true  // 设置响应状态为 true
  
  try {
    const userMessage = messageInput.value
    const currentTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })

    // 立即显示用户消息（保留原始消息，包含图片标记）
    const userMsg = {
      id: Date.now(),
      role: 'user',
      content: userMessage,
      time: currentTime
    }
    messages.value.push(userMsg)
    
    messageInput.value = ''
    await scrollToBottom()
    
    // 提取消息中的图片ID
    const imageIds = extractImageIds(userMessage)
    // 提取纯文本内容（移除图片标记）
    const pureText = extractPureText(userMessage)
    
    // 构建请求数据
    const data = {
      query: pureText,
      response_mode: 'streaming',
      user: USER_ID,
      inputs: {},
      callback: async (message, chunk) => {  // 确保接收 chunk 参数
        console.log('Received chunk:', chunk)  // 添加日志
        if (currentConversation.value?.id === data.conversation_id && isResponding.value) {
          // 从 chunk 中获取 task_id
          if (chunk && chunk.task_id && !currentTaskId.value) {
            console.log('Setting task_id:', chunk.task_id)  // 添加日志
            currentTaskId.value = chunk.task_id
          }
          
          isWaiting.value = false
          streamingMessage.value = message
          sending.value = false
          await scrollToBottom()
        }
      }
    }
    
    // 如果有图片，添加文件信息到请求体
    if (imageIds.length > 0) {
      data.files = imageIds.map(id => ({
        type: 'image',
        transfer_method: 'local_file',
        upload_file_id: id
      }))
    }
    
    if (currentConversation.value?.id) {
      data.conversation_id = currentConversation.value.id
    }
    
    const res = await apiSendMessage(data)
    
    // 如果响应中直接包含 task_id，也保存它
    if (res.task_id) {
      console.log('Setting task_id from response:', res.task_id)  // 添加日志
      currentTaskId.value = res.task_id
    }
    
    // 如果是新会话，更新会话列表和当前会话
    if (!currentConversation.value?.id && res.conversation_id) {
      await fetchConversations()
      currentConversation.value = conversations.value.find(c => c.id === res.conversation_id)
      
      if (res.message_id) {
        await renameConversation(res.conversation_id, {
          auto_generate: true,
          user: USER_ID
        })
        await fetchConversations()
        currentConversation.value = conversations.value.find(c => c.id === res.conversation_id)
      }
    }
    
    // 等待一小段时间确保服务器已处理完消息
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 保存当前的流式消息，并移除可能的重复内容
    let finalStreamMessage = streamingMessage.value
    // 检查并移除重复的 \boxed{} 内容
    const boxedPattern = /\\\boxed{.*?}/g
    const matches = finalStreamMessage.match(boxedPattern)
    if (matches && matches.length > 1) {
      const lastBoxed = matches[matches.length - 1]
      finalStreamMessage = finalStreamMessage.replace(boxedPattern, '').trim() + '\n\n' + lastBoxed
    }
    
    // 清空流式消息，避免重复显示
    streamingMessage.value = ''
    
    // 更新消息缓存
    if (currentConversation.value?.id) {
      if (!messageCache.value[currentConversation.value.id]) {
        messageCache.value[currentConversation.value.id] = []
      }
      
      // 添加新消息到缓存
      messageCache.value[currentConversation.value.id] = [
        ...messageCache.value[currentConversation.value.id].filter(msg => 
          !(msg.content === userMessage || msg.content === finalStreamMessage)
        ),
        {
          id: res.message_id,
          role: 'user',
          content: userMessage,
          time: currentTime
        },
        {
          id: res.message_id,
          role: 'assistant',
          content: finalStreamMessage,
          time: currentTime
        }
      ]
      
      // 更新显示的消息
      messages.value = messageCache.value[currentConversation.value.id]
    }
    
    await scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    isResponding.value = false
    sending.value = false
    isWaiting.value = false
  }
}

// 修改停止响应的方法
const stopResponse = async () => {
  console.log('Stopping response with task_id:', currentTaskId.value)  // 添加日志
  
  if (!currentTaskId.value) {
    console.log('No task_id available')  // 添加日志
    // 如果没有任务ID，直接重置状态
    isResponding.value = false
    sending.value = false
    isWaiting.value = false
    streamingMessage.value = ''
    return
  }
  
  try {
    // 从 localStorage 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const username = userInfo.username

    if (!username) {
      ElMessage.error('用户未登录')
      return
    }

    console.log('Sending stop request for task:', currentTaskId.value)  // 添加日志
    
    // 调用停止接口
    const response = await fetch(`/v1/chat-messages/${currentTaskId.value}/stop`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${import.meta.env.VITE_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user: username
      })
    })

    console.log('Stop response status:', response.status)  // 添加日志

    if (!response.ok) {
      throw new Error('停止响应失败')
    }

    const result = await response.json()
    console.log('Stop response result:', result)  // 添加日志
    
    // 重置状态
    isResponding.value = false
    sending.value = false
    isWaiting.value = false
    
    // 保存当前的回答
    if (streamingMessage.value && currentConversation.value?.id) {
      const currentTime = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      
      // 将中断的回答添加到消息列表
      if (messageCache.value[currentConversation.value.id]) {
        messageCache.value[currentConversation.value.id].push({
          id: Date.now(),
          role: 'assistant',
          content: streamingMessage.value,
          time: currentTime
        })
        
        // 更新显示的消息
        messages.value = messageCache.value[currentConversation.value.id]
      }
    }
    
    // 清空流式消息和任务ID
    streamingMessage.value = ''
    currentTaskId.value = null

    ElMessage.success('已停止响应')
  } catch (error) {
    console.error('停止响应失败:', error)
    ElMessage.error('停止响应失败')
  }
}

// 处理文件上传
const handleFileChange = (file) => {
  selectedFiles.value.push(file.raw)
}

// 处理重命名
const handleRename = async (conv) => {
  const newName = await ElMessageBox.prompt('请输入新的会话名称', '重命名会话', {
    inputValue: conv.name
  })
  
  if (newName.value) {
    // 不等待重命名完成，异步处理
    renameConversation(conv.id, {
      name: newName.value,
      auto_generate: true,
      user: USER_ID
    }).then(() => {
      // 重命名成功后异步更新会话列表
      fetchConversations()
    }).catch(error => {
      console.error('重命名失败:', error)
      ElMessage.error('重命名失败')
    })
  }
}

// 处理反馈
const handleFeedback = async (messageId, rating, content) => {
  try {
    await sendFeedback(messageId, rating, content)
    
    // 更新消息的反馈状态
    const msgIndex = messages.value.findIndex(msg => msg.id === messageId)
    if (msgIndex !== -1) {
      messages.value[msgIndex].liked = rating
    }
    
    // 更新缓存中的反馈状态
    if (currentConversation.value?.id) {
      const cachedMessages = messageCache.value[currentConversation.value.id]
      if (cachedMessages) {
        const cachedMsgIndex = cachedMessages.findIndex(msg => msg.id === messageId)
        if (cachedMsgIndex !== -1) {
          cachedMessages[cachedMsgIndex].liked = rating
        }
      }
    }
    
    // 根据反馈类型显示不同的提示
    const message = rating === 'like' ? '感谢您的点赞！' : 
                   rating === 'dislike' ? '感谢您的反馈！' : 
                   '已取消反馈'
    
    ElMessage.success(message)
  } catch (error) {
    console.error('发送反馈失败:', error)
    ElMessage.error('发送反馈失败')
  }
}

// 修改 createNewConversation 函数
const createNewConversation = async () => {
  try {
    // 清空所有相关状态
    streamingMessage.value = ''
    messages.value = []
    currentConversation.value = null
    messageInput.value = '' // 清空输入框
    sending.value = false   // 重置发送状态
    isWaiting.value = false // 重置等待状态
    
    // 创建新会话，但不发送初始消息
    currentConversation.value = null
    
    // 更新会话列表
    await fetchConversations()
    
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
  }
}

// 复制消息，只复制答案部分
const copyMessage = (content) => {
  if (!content) return
  
  // 使用 </details> 标签分割内容
  const parts = content.split('</details>')
  // 如果存在 </details> 标签，取最后一部分（答案部分）
  const cleanContent = parts.length > 1 ? parts[parts.length - 1].trim() : content
  
  navigator.clipboard.writeText(cleanContent).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 删除会话
const handleDelete = async (conv) => {
  try {
    await ElMessageBox.confirm('确定要删除这个会话吗？', '提示', {
      type: 'warning'
    })
    
    await deleteConversation(conv.id)
    
    // 删除会话相关的所有缓存
    delete messageCache.value[conv.id]  // 删除消息缓存
    messages.value = []  // 清空当前显示的消息
    
    // 重新获取会话列表
    await fetchConversations()
    
    // 如果删除的是当前会话
    if (currentConversation.value?.id === conv.id) {
      currentConversation.value = null
      // 如果还有其他会话，选择第一个
      if (conversations.value.length > 0) {
        await selectConversation(conversations.value[0])
      }
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会话失败:', error)
      ElMessage.error('删除会话失败')
    }
  }
}

const handleLogout = async () => {
  try {
    await logout()
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    router.push('/login')
  } catch (error) {
    console.error('退出失败:', error)
    ElMessage.error('退出失败')
  }
}

// 在组件卸载时清理所有缓存
onUnmounted(() => {
  messageCache.value = {}  // 清除消息缓存
  messages.value = []      // 清空消息列表
})

// 添加清除缓存的方法
const clearMessageCache = (conversationId) => {
  if (conversationId) {
    delete messageCache.value[conversationId]
  } else {
    messageCache.value = {}
  }
}

// 强制刷新消息列表的方法
const forceRefreshMessages = async (conversationId) => {
  clearMessageCache(conversationId)
  await fetchMessages(conversationId)
}

// 修改 handlePaste 函数
const handlePaste = async (event) => {
  const items = event.clipboardData?.items
  if (!items) return

  // 从 localStorage 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
  const username = userInfo.username

  if (!username) {
    ElMessage.error('用户未登录')
    return
  }

  for (const item of items) {
    if (item.type.startsWith('image/')) {
      const file = item.getAsFile()
      if (file) {
        try {
          const loadingInstance = ElMessage.info({
            message: '正在上传图片...',
            duration: 0
          })
          
          const formData = new FormData()
          formData.append('file', file)
          formData.append('user', username)  // 使用登录用户的用户名
          
          // 使用配置文件中的 API Key
          const response = await fetch('/v1/files/upload', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${import.meta.env.VITE_API_KEY}`
            },
            body: formData
          })
          
          if (!response.ok) {
            throw new Error('上传失败')
          }
          
          const data = await response.json()
          loadingInstance.close()
          
          if (data.id) {
            // 在输入框中插入图片标记
            const imageMarkdown = `![${data.name}](${data.id})\n`
            messageInput.value += imageMarkdown
            ElMessage.success('图片上传成功')
          }
        } catch (error) {
          console.error('图片上传失败:', error)
          ElMessage.error('图片上传失败')
        }
      }
    }
  }
}

onMounted(async () => {
  await fetchConversations()
  // 如果有会话，加载第一个会话的消息
  if (conversations.value.length > 0) {
    await selectConversation(conversations.value[0])
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background-color: #ffffff;
}

.conversation-list {
  width: 260px;
  background-color: #202123;
  display: flex;
  flex-direction: column;
  color: #ffffff;
  height: 100vh; /* 确保占满整个高度 */
}

.list-header {
  padding: 12px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.new-chat-btn {
  width: 100%;
  margin-top: 8px;
  background-color: transparent;
  border: 1px solid #4b5563;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.new-chat-btn:hover {
  background-color: #2d2d2d;
}

.conversation-groups {
  padding: 12px;
}

.group-title {
  font-size: 12px;
  color: #8e8ea0;
  padding: 8px 0;
}

.conversation-item {
  padding: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  border-radius: 6px;
  margin-bottom: 4px;
}

.conversation-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.conversation-item:hover {
  background-color: #2d2d2d;
}

.conversation-item.active {
  background-color: #343541;
}

.item-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
  z-index: 1;
}

.conversation-item:hover .item-actions {
  opacity: 1;
}

.item-actions .el-icon {
  padding: 4px;
  border-radius: 4px;
  cursor: pointer;
}

.item-actions .el-icon:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
}

.message-list {
  flex: 1;
  overflow: hidden;
}

.message-wrapper {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.message-item {
  display: flex;
  gap: 16px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
}

.user .avatar {
  background-color: #409eff;
  color: #ffffff;
}

.assistant .avatar {
  background-color: #95de64;
  color: #ffffff;
}

.avatar :deep(.el-icon) {
  font-size: 20px;
}

.message-content {
  flex: 1;
  min-width: 0;
  overflow-x: auto;  /* 允许代码块横向滚动 */
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.message-role {
  font-weight: 500;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.message-actions .el-icon {
  cursor: pointer;
  transition: all 0.3s;
  opacity: 0.6;
}

.message-actions .el-icon:hover {
  transform: scale(1.1);
  opacity: 1;
}

.message-actions .el-icon.active {
  opacity: 1;
  color: #409eff;
}

/* 点踩按钮激活状态 */
.message-actions .el-icon.active.warning {
  color: #f56c6c;
}

.input-area {
  border-top: 1px solid #f0f0f0;
  padding: 24px;
}

.input-wrapper {
  max-width: 800px;
  margin: 0 auto;
  position: relative;
}

.input-wrapper :deep(.el-textarea__inner) {
  padding-right: 44px;
  border-radius: 8px;
  resize: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  min-height: 44px !important;
}

.input-wrapper :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

.send-button {
  position: absolute;
  right: 6px;
  bottom: 6px;
  transition: all 0.3s ease;
}

.send-button:hover {
  transform: scale(1.05);
}

/* 停止按钮样式 */
.send-button.is-responding {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.send-button.is-responding:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.input-tip {
  text-align: center;
  color: #8e8ea0;
  font-size: 12px;
  margin-top: 8px;
  display: flex;
  justify-content: center;
  gap: 8px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #8e8ea0;
  animation: typing 1s infinite ease-in-out;
}

@keyframes typing {
  0%, 100% {
    opacity: 0.4;
  }
  50% {
    opacity: 1;
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .conversation-list {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 100;
    transform: translateX(0);
  }

  .mobile-hidden {
    transform: translateX(-100%);
  }

  .message-wrapper {
    padding: 12px;
  }

  .input-area {
    padding: 16px;
  }
}

/* 添加 Markdown 样式 */
.markdown-body {
  color: #24292e;
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body code {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 6px;
  font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
}

.markdown-body pre {
  position: relative;
  padding: 16px;
  background-color: #f6f8fa;
  border-radius: 6px;
  margin: 8px 0;
}

.markdown-body pre code {
  display: block;
  overflow-x: auto;
  padding: 0;
  font-size: 14px;
  line-height: 1.45;
  background: transparent;
}

/* 代码块语言标识 */
.markdown-body pre code::before {
  content: attr(class);
  position: absolute;
  top: 0;
  right: 0;
  padding: 4px 8px;
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  border-bottom-left-radius: 4px;
}

/* 行内代码样式 */
.markdown-body code:not(pre code) {
  padding: 2px 6px;
  margin: 0 2px;
  font-size: 90%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
}

/* 高亮主题定制 */
.hljs {
  display: block;
  overflow-x: auto;
  padding: 1em;
  color: #333;
  background: #f8f8f8;
}

.hljs-comment,
.hljs-quote {
  color: #998;
  font-style: italic;
}

.hljs-keyword,
.hljs-selector-tag,
.hljs-subst {
  color: #d73a49;
}

.hljs-string,
.hljs-doctag {
  color: #032f62;
}

.hljs-title,
.hljs-section,
.hljs-selector-id {
  color: #6f42c1;
}

.hljs-type,
.hljs-class {
  color: #458;
  font-weight: bold;
}

.hljs-literal,
.hljs-number {
  color: #005cc5;
}

.hljs-tag,
.hljs-name,
.hljs-attribute {
  color: #22863a;
}

.markdown-body p {
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body table {
  display: block;
  width: 100%;
  overflow: auto;
  margin-top: 0;
  margin-bottom: 16px;
  border-spacing: 0;
  border-collapse: collapse;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

/* 代码块样式 */
.code-block {
  margin: 16px 0;
  border-radius: 8px;
  overflow: hidden;
  background: #1E1E1E;
}

.code-header {
  padding: 8px 16px;
  background: #2D2D2D;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-lang {
  color: #fff;
  font-size: 12px;
  font-family: monospace;
  text-transform: uppercase;
}

.code-block pre {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
}

.code-block code {
  font-family: 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  padding: 0;
  background: transparent !important;
}

/* 修改 Markdown 样式 */
.markdown-body pre {
  padding: 0;
  background: transparent;
  margin: 0;
}

.markdown-body pre code {
  padding: 0;
}

.markdown-body code {
  font-family: 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
}

/* 行内代码样式 */
.markdown-body :not(pre) > code {
  padding: 2px 6px;
  margin: 0 2px;
  font-size: 90%;
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 4px;
  color: #24292f;
}

/* 滚动条样式 */
.code-block pre::-webkit-scrollbar {
  height: 8px;
}

.code-block pre::-webkit-scrollbar-thumb {
  background: #4a4a4a;
  border-radius: 4px;
}

.code-block pre::-webkit-scrollbar-track {
  background: #2d2d2d;
}

/* 高亮主题覆盖 */
.hljs {
  background: transparent !important;
  padding: 0 !important;
}

.logout-btn {
  padding: 8px;
}

/* 修改点赞按钮样式 */
.message-actions .thumb {
  transform: scale(1.2);  /* 稍微放大图标 */
}

.message-actions .el-icon.active .thumb {
  transform: scale(1.4);  /* 激活状态更大 */
}

/* 修改点赞和不喜欢的颜色 */
.message-actions .el-icon.active {
  opacity: 1;
}

.message-actions .el-icon.active:has(.thumb) {
  color: #67c23a;  /* 点赞为绿色 */
}

.message-actions .el-icon.active:has(.thumb[class*="bottom"]) {
  color: #f56c6c;  /* 不喜欢为红色 */
}

/* 悬停效果 */
.message-actions .el-icon:hover .thumb {
  transform: scale(1.3);
}

/* 添加新的样式 */
.list-footer {
  margin-top: auto;
  padding: 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.logout-btn {
  width: 100%;
  background-color: transparent;
  border: none;
  color: #ff6b6b;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background-color: rgba(255, 107, 107, 0.1);
  color: #ff4757;
}

.logout-btn .el-icon {
  margin-right: 4px;
}

/* 修改滚动区域样式，使其自适应剩余空间 */
.conversation-list .el-scrollbar {
  flex: 1;
  overflow: hidden;
}

/* 添加欢迎界面样式 */
.welcome-screen {
  padding: 60px 20px;
  text-align: center;
  max-width: 600px;
  margin: 0 auto;
}

.welcome-title {
  font-size: 32px;
  color: #333;
  margin-bottom: 40px;
  font-weight: 500;
}

.suggestions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.suggestion-row {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.suggestion-item {
  flex: 1;
  max-width: 200px;
  padding: 20px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 10px;
}

.suggestion-item:hover {
  background-color: #f3f4f6;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.suggestion-item .el-icon {
  font-size: 20px;
  color: #666;
}

.suggestion-item span {
  font-size: 14px;
  color: #333;
}

/* 确保欢迎界面在移动端也能正常显示 */
@media screen and (max-width: 768px) {
  .welcome-screen {
    padding: 40px 16px;
  }
  
  .suggestion-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .suggestion-item {
    max-width: 100%;
  }
}
</style> 